package cn.minds.capture.dispatch.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingQueue;

import cn.minds.capture.dispatch.task.Task;
import cn.minds.capture.dispatch.task.TaskHandlerFacotry;

public class ClientManager {
	private final static LinkedBlockingQueue<Task> queues = new LinkedBlockingQueue<Task>(100);
	private List<TaskClient> clients = new CopyOnWriteArrayList<TaskClient>();
	private Map<String, Task> tasks = new HashMap<String, Task>();
	private TaskHandlerFacotry taskHandlerFacotry;

	public ClientManager(TaskHandlerFacotry taskHandlerFacotry) {
		super();
		this.taskHandlerFacotry = taskHandlerFacotry;
	}

	public TaskHandlerFacotry getTaskHandlerFacotry() {
		return taskHandlerFacotry;
	}

	public void setTaskHandlerFacotry(TaskHandlerFacotry taskHandlerFacotry) {
		this.taskHandlerFacotry = taskHandlerFacotry;
	}

	public void addClient(String host, int port) {
		clients.add(new TaskClient(this, host, port));
	}

	// 移除
	public void removeClient(TaskClient taskClient) {
		clients.remove(taskClient);
	}

	// 添加任务
	public void addTask(Task task) {
		try {
			queues.put(task);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	// 从任务列表中拿一个
	public Task getTask() {
		return queues.poll();
	}

	public List<Task> getTasks() {
		List<Task> task = new ArrayList<Task>();
		setMap(tasks, task);
		return task;
	}

	private void setMap(Map<String, Task> tasks, List<Task> task) {
		Set<Entry<String, Task>> ts = tasks.entrySet();
		if (tasks != null) {
			for (Entry<String, Task> entry : ts) {
				task.add(entry.getValue());
			}
		}
	}

	public Task removeTask(String id) {
		// 保存到日子
		return tasks.remove(id);
	}

}
